/**
 * Copyright (c) 2009 Collaborative Development Group, C.S. Dept., University of Bari
 *
 * All rights reserved. This program and the accompanying materials are made available under
 * the terms of the Eclipse Public License v1.0  which accompanies this distribution, and is 
 * available at http://www.eclipse.org/legal/epl-v10.html
 */
package it.uniba.di.cdg.penelope.events;

import java.util.HashMap;
import java.util.Map;

import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;

import com.google.inject.Inject;
import static it.uniba.di.cdg.penelope.events.Utilities.getTopicId;

/**
 * Implementation of {@link IEventHelper} based on the standard {@link EventAdmin} OSGi service.
 * TODO Write Unit Test 
 */
public class EventHelper implements IEventHelper {
	private final EventAdmin eventAdmin;

	@Inject
	public EventHelper( EventAdmin eventAdmin ) {
		super();
		this.eventAdmin = eventAdmin;
	}

	/* (non-Javadoc)
	 * @see it.uniba.di.cdg.penelope.events.IEventSupport#fire(java.lang.Object)
	 */
	@Override
	public <T> void fire( T event ) {
		eventAdmin.sendEvent( wrapEvent( event ) );
	}

	/* (non-Javadoc)
	 * @see it.uniba.di.cdg.penelope.events.IEventHelper#fireAsynch(java.lang.Object)
	 */
	@Override
	public <T> void fireAsynch( T event ) {
		eventAdmin.postEvent( wrapEvent( event ) );
	}

	private static <T> Event wrapEvent( T event ) {
		String topicId = getTopicId( event.getClass() );
		Map<String, Object> args = new HashMap<String, Object>();
		args.put( APP_EVENT, event );
		return new Event( topicId, args );
	}
}
